# == Schema Information
# Schema version: 2
#
# Table name: records
#
#  id           :integer(4)      not null, primary key
#  name         :string(255)
#  release_type :string(255)
#  description  :text
#  artist_id    :integer(4)
#  created_at   :datetime
#  updated_at   :datetime
#

class Record < ActiveRecord::Base
  belongs_to :artist, :class_name => "Artist", :foreign_key => "artist_id"
  has_many :tracks, :class_name => "Track"
  
  validates_presence_of :name, :release_type, :description, :artist_id
  validates_associated :tracks
  
  after_update :save_tracks
  
  def artist_name
    artist.name if artist
  end
  
  def new_track_attributes=(track_attributes)
    track_attributes.each do |attributes|
      tracks.build(attributes)
    end
  end
  
  def existing_track_attributes=(track_attributes)
    tracks.reject(&:new_record?).each do |track|  
      attributes = track_attributes[track.id.to_s]
      if attributes
        track.attributes = attributes
      else
        tracks.delete(track)
      end  
    end
  end
  
  def save_tracks
    tracks.each do |track|
      track.save(false)
    end
  end
  
end
